package com.liuyang.demo.mybatis.enums.handler;

import com.google.common.collect.Maps;
import com.liuyang.demo.json.JSONCamelUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

/**
 * @描述 :
 * @作者 :	cs
 * @日期 :	2018/7/10
 * @时间 :	12:25
 */
public class MapStringHandler extends BaseTypeHandler<Map<String, String>> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<String, String> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null) {
            ps.setString(i, JSONCamelUtils.writeValue(parameter));
        }
    }

    @Override
    public Map<String, String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 根据数据库存储类型决定获取类型
        String data = rs.getString(columnName);
        return rs.wasNull() ? null : convert(data);
    }

    @Override
    public Map<String, String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String data = rs.getString(columnIndex);
        return rs.wasNull() ? null : convert(data);
    }

    @Override
    public Map<String, String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String data = cs.getString(columnIndex);
        return cs.wasNull() ? null : convert(data);
    }

    private Map<String, String> convert(String value) {
        if (value == null || value.isEmpty()) {
            try {
                return Maps.newHashMap();
            } catch (Exception e) {
                return null;
            }
        }
        return JSONCamelUtils.readMapValue(value, String.class, String.class);
    }

}
